package com.books.controller.alipay;

import com.alipay.api.AlipayApiException;
import com.books.config.AliPayTemplate;
import com.books.model.vo.PayVo;
import com.books.service.alipay.OrderService;
import com.books.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.TimeUnit;

/**
 * @author ZhouRui
 * @title: 码上就来
 * @projectName cbstore-spring-boot
 * @description: TODO
 * @date 2021/10/1320:14
 */
@Controller
@Slf4j
public class PayWebController {
    @Autowired
    private AliPayTemplate aliPayTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired(required = false)
    private OrderService orderService;
    @Autowired
    private PayVo payVo;

    /**
     * 调用该方法会去到支付宝支付
     * @return 返回的是支付宝的页面 - produces = "text/html"
     * @throws AlipayApiException 支付异常
     */
    @GetMapping(value = "/payOrder")
    @ResponseBody
    public String payOrder(String id) throws AlipayApiException {
        // 这里订单号应该是前端传过来的，即orderSn
        // 但是为了Demo方便测试，前端传来的是一个固定的数字(按理说前端应该传的是具体订单号)
        // 支付宝这个订单号又不能重复，所以在这个方法里实际使用了一个雪花算法生成的订单号，即noStr
        String noStr = SnowflakeIdWorker.generateId() + "";

        log.info("订单ID：{}", noStr);
        // 正常的应该是传入前端传来的orderSn
        payVo = orderService.getOrderPay(noStr,id);
        System.out.println(payVo);
        redisTemplate.opsForValue().set("pcode"+noStr,payVo,30, TimeUnit.MINUTES);
        return aliPayTemplate.pay(payVo);
    }
}
